use std::os::raw::{c_int, c_char};
use std::ptr;
use std::ffi::CString;

use ratatui::backend::{Backend, CrosstermBackend};
use ratatui::Terminal;
use crossterm::terminal::{enable_raw_mode, disable_raw_mode};
use std::io::{stdout, Stdout};

use crate::RatatuiResult;

/// 后端类型枚举
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RatatuiBackendType {
    Crossterm = 0,
    // 未来可以添加其他后端
    // Termion = 1,
    // TestBackend = 2,
}

/// 后端信息结构
#[repr(C)]
#[derive(Debug, Clone)]
pub struct RatatuiBackendInfo {
    pub backend_type: RatatuiBackendType,
    pub name: String,
    pub version: String,
    pub features: Vec<String>,
    pub supported: bool,
}

impl RatatuiBackendInfo {
    /// 获取Crossterm后端信息
    pub fn crossterm() -> Self {
        RatatuiBackendInfo {
            backend_type: RatatuiBackendType::Crossterm,
            name: "Crossterm".to_string(),
            version: "0.27.0".to_string(),
            features: vec![
                "跨平台支持".to_string(),
                "鼠标事件".to_string(),
                "键盘事件".to_string(),
                "终端大小调整".to_string(),
                "颜色支持".to_string(),
                "样式修饰符".to_string(),
            ],
            supported: true,
        }
    }
}

/// 后端管理器结构
pub struct RatatuiBackendManager {
    pub current_backend: RatatuiBackendType,
    pub available_backends: Vec<RatatuiBackendInfo>,
}

impl RatatuiBackendManager {
    /// 创建新的后端管理器
    pub fn new() -> Self {
        let mut manager = RatatuiBackendManager {
            current_backend: RatatuiBackendType::Crossterm,
            available_backends: Vec::new(),
        };
        
        // 添加可用的后端
        manager.available_backends.push(RatatuiBackendInfo::crossterm());
        
        manager
    }
    
    /// 检查后端是否可用
    pub fn is_backend_available(&self, backend_type: RatatuiBackendType) -> bool {
        self.available_backends
            .iter()
            .any(|info| info.backend_type == backend_type && info.supported)
    }
    
    /// 设置当前后端
    pub fn set_backend(&mut self, backend_type: RatatuiBackendType) -> Result<(), String> {
        if self.is_backend_available(backend_type) {
            self.current_backend = backend_type;
            Ok(())
        } else {
            Err(format!("Backend {:?} is not available", backend_type))
        }
    }
    
    /// 获取当前后端信息
    pub fn get_current_backend_info(&self) -> Option<&RatatuiBackendInfo> {
        self.available_backends
            .iter()
            .find(|info| info.backend_type == self.current_backend)
    }
}

/// 创建后端管理器
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_new() -> *mut RatatuiBackendManager {
    let manager = RatatuiBackendManager::new();
    Box::into_raw(Box::new(manager))
}

/// 释放后端管理器
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_free(manager: *mut RatatuiBackendManager) {
    if !manager.is_null() {
        unsafe {
            let _ = Box::from_raw(manager);
        }
    }
}

/// 获取可用后端数量
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_get_backend_count(
    manager: *const RatatuiBackendManager,
) -> c_int {
    if manager.is_null() {
        return 0;
    }
    
    unsafe {
        let manager_ref = &*manager;
        manager_ref.available_backends.len() as c_int
    }
}

/// 获取后端信息
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_get_backend_info(
    manager: *const RatatuiBackendManager,
    index: c_int,
    backend_type: *mut RatatuiBackendType,
    name: *mut *mut c_char,
    version: *mut *mut c_char,
) -> c_int {
    if manager.is_null() || backend_type.is_null() || name.is_null() || version.is_null() {
        return RatatuiResult::ErrorNullPointer as c_int;
    }
    
    unsafe {
        let manager_ref = &*manager;
        if index < 0 || index >= manager_ref.available_backends.len() as c_int {
            return RatatuiResult::ErrorInvalidArgument as c_int;
        }
        
        let backend_info = &manager_ref.available_backends[index as usize];
        
        *backend_type = backend_info.backend_type;
        
        // 设置名称
        match CString::new(backend_info.name.clone()) {
            Ok(c_string) => *name = c_string.into_raw(),
            Err(_) => return RatatuiResult::ErrorInvalidArgument as c_int,
        }
        
        // 设置版本
        match CString::new(backend_info.version.clone()) {
            Ok(c_string) => *version = c_string.into_raw(),
            Err(_) => return RatatuiResult::ErrorInvalidArgument as c_int,
        }
        
        RatatuiResult::Ok as c_int
    }
}

/// 检查后端是否可用
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_is_available(
    manager: *const RatatuiBackendManager,
    backend_type: RatatuiBackendType,
) -> bool {
    if manager.is_null() {
        return false;
    }
    
    unsafe {
        let manager_ref = &*manager;
        manager_ref.is_backend_available(backend_type)
    }
}

/// 设置当前后端
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_set_backend(
    manager: *mut RatatuiBackendManager,
    backend_type: RatatuiBackendType,
) -> c_int {
    if manager.is_null() {
        return RatatuiResult::ErrorNullPointer as c_int;
    }
    
    unsafe {
        let manager_ref = &mut *manager;
        match manager_ref.set_backend(backend_type) {
            Ok(_) => RatatuiResult::Ok as c_int,
            Err(_) => RatatuiResult::ErrorInvalidArgument as c_int,
        }
    }
}

/// 获取当前后端类型
#[no_mangle]
pub extern "C" fn ratatui_backend_manager_get_current_backend(
    manager: *const RatatuiBackendManager,
) -> RatatuiBackendType {
    if manager.is_null() {
        return RatatuiBackendType::Crossterm;
    }
    
    unsafe {
        let manager_ref = &*manager;
        manager_ref.current_backend
    }
}

/// 获取后端特性数量
#[no_mangle]
pub extern "C" fn ratatui_backend_get_feature_count(
    manager: *const RatatuiBackendManager,
    backend_type: RatatuiBackendType,
) -> c_int {
    if manager.is_null() {
        return 0;
    }
    
    unsafe {
        let manager_ref = &*manager;
        if let Some(info) = manager_ref.available_backends
            .iter()
            .find(|info| info.backend_type == backend_type) {
            info.features.len() as c_int
        } else {
            0
        }
    }
}

/// 获取后端特性
#[no_mangle]
pub extern "C" fn ratatui_backend_get_feature(
    manager: *const RatatuiBackendManager,
    backend_type: RatatuiBackendType,
    feature_index: c_int,
) -> *mut c_char {
    if manager.is_null() {
        return ptr::null_mut();
    }
    
    unsafe {
        let manager_ref = &*manager;
        if let Some(info) = manager_ref.available_backends
            .iter()
            .find(|info| info.backend_type == backend_type) {
            if feature_index >= 0 && feature_index < info.features.len() as c_int {
                let feature = &info.features[feature_index as usize];
                match CString::new(feature.clone()) {
                    Ok(c_string) => c_string.into_raw(),
                    Err(_) => ptr::null_mut(),
                }
            } else {
                ptr::null_mut()
            }
        } else {
            ptr::null_mut()
        }
    }
}

/// 释放C字符串
#[no_mangle]
pub extern "C" fn ratatui_backend_free_string(s: *mut c_char) {
    if !s.is_null() {
        unsafe {
            let _ = CString::from_raw(s);
        }
    }
}
